#!/usr/bin/env bash

REALPATH=$(realpath $0)
WORK_DIR=$(cd $(dirname $REALPATH)/.. && pwd)

# Generate self-sign HTTPS crt and file.
if [[ ! -f ${WORK_DIR}/containers/ssl/nginx.key ]]; then
  mkdir -p ${WORK_DIR}/containers/ssl &&
  rm -f ${WORK_DIR}/containers/ssl/nginx.key ${WORK_DIR}/containers/ssl/nginx.crt &&
  openssl genrsa -out ${WORK_DIR}/containers/ssl/nginx.key 2048 &&
  openssl req -new -x509 -key ${WORK_DIR}/containers/ssl/nginx.key -out ${WORK_DIR}/containers/ssl/nginx.crt \
    -days 3650 -subj "/C=CN/ST=Beijing/L=Beijing/O=Me/OU=Me/CN=ossrs.net"
  if [[ $? -ne 0 ]]; then echo "Create self-sign cert failed"; exit 1; fi
fi

# We will generate the nginx.vhost.conf for nginx, here we know the absolute path, because the path in NGINX configuration
# should be absolute path or relative to the prefix path, see https://serverfault.com/a/777408
cat << END > containers/conf/conf.d/nginx.vhost.conf
# !!! Important: SRS will restore this file during each upgrade, please never modify it.

# Configurations apply to http section.
include ${WORK_DIR}/containers/conf/conf.d/nginx.http.conf;

# SRS Cloud default server.
server {
  # Configurations apply to server section.
  include ${WORK_DIR}/containers/conf/conf.d/nginx.server.conf;

  # We serve the home at local files.
  root ${WORK_DIR}/containers/www;

  # Load configuration files for the default server block.
  include ${WORK_DIR}/containers/conf/default.d/*.conf;
}
END

